package leecode.LinkedList.SingleLinkedList;

public class MyLinkedList {
    class Node{
        public int data;
        public Node next;
        public Node(int data){
            this.data=data;
        }
    }

    Node head;
    int size;
    public MyLinkedList() {
        this.head=null;
        this.size=0;
    }

    public int get(int index) {
        Node point = head;
        if(index>=size || index<0){
            return -1;
        } else if (index==0 && size==0) {
            return -1;
        } else {
            for (int i = 0; i < index; i++) {
                point = point.next;
            }
            return point.data;
        }

    }

    public void addAtHead(int val) {
        Node node = new Node(val);
        node.next=head;
        head=node;
        size++;
    }

    public void addAtTail(int val) {
        if (size==0){
            addAtHead(val);
        }else {
            Node point = head;
            for (int i = 0; i < size-1; i++) {
                point = point.next;
            }
            point.next = new Node(val);
            size++;
        }
    }

    public void addAtIndex(int index, int val) {
        if(index<=0){
            addAtHead(val);
        }else if(index==size){
            addAtTail(val);
        }else if(index>size){
            System.out.println("插入位置有误");
        }else{
            Node point = head;
            for (int i = 0; i < index-1; i++) {
                point = point.next;
            }
            Node node = new Node(val);
            node.next=point.next;
            point.next=node;
            size++;
        }
    }

    public void deleteAtIndex(int index) {
        if(index<0 || index>=size){

        } else if(index==0){
            head=head.next;
            size--;
        } else {
            Node point = head;
            for (int i = 0; i < index-1; i++) {
                point = point.next;
            }
            point.next=point.next.next;
            size--;
        }
    }

    public static void main(String[] args) {
        MyLinkedList list = new MyLinkedList();
        list.addAtHead(1);
        list.addAtTail(3);
        list.addAtIndex(1,2);
        System.out.println(list.get(1));
        list.deleteAtIndex(1);
        System.out.println(list.get(1));
        System.out.println(list.get(1));
        System.out.println(list.get(3));
        list.deleteAtIndex(3);
        list.deleteAtIndex(0);
        System.out.println(list.get(0));
        list.deleteAtIndex(0);
        System.out.println("链表长度："+list.size);
        System.out.println(list.get(0));

    }
}
